package com.bieber.common;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by bieber on 2015/9/5.
 */
public class LockDemo  {


    public void otherThread(final ReentrantLock lock){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("other thread getting lock");
                lock.lock();
                System.out.println("other thread got lock");
                lock.unlock();
            }
        }).start();
    }


    public void lock(){
        ReentrantLock lock = new ReentrantLock();
        System.out.println(Thread.currentThread().getName()+"getting lock");
        lock.lock();
        Condition condition = lock.newCondition();
        otherThread(lock);
        System.out.println(Thread.currentThread().getName()+"got lock");
        try {
            System.out.println(Thread.currentThread().getName()+"await..");
            condition.await(10000, TimeUnit.MILLISECONDS);
            System.out.println(Thread.currentThread().getName()+"awaited..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "unlocking");
        lock.unlock();
        System.out.println(Thread.currentThread().getName() + "unlock");
    }
    public static void main(String[] args) throws InterruptedException {
        final LockDemo demo = new LockDemo();
        for(int i=0;i<1;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.lock();
                }
            }).start();
            Thread.sleep(1000);
        }
    }

}
